package org.mymybatis.transaction.jdbc;

import org.mymybatis.transaction.Transaction;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Auther: sh
 * @Version 1.0
 * @Description: JDBC事务管理器
 */
public class JDBCTransaction implements Transaction {

    /**
     * 连接对象，控制事务时需要
     */
    private Connection conn;

    /**
     * 数据源对象
     */
    private DataSource dataSource;

    private boolean autoCommit = false;   // true 自动提交   false 手动提交

    /**
     * 创建事务管理器对象
     *
     * @param dataSource
     * @param autoCommit
     */
    public JDBCTransaction(DataSource dataSource, boolean autoCommit) {
        this.dataSource = dataSource;
        this.autoCommit = autoCommit;
    }




    @Override
    public void commit()  {
        try {
            getConnection().commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void rollback() {
        try {
            getConnection().rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void close() {
        try {
            getConnection().close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 打开连接
     */
    @Override
    public void openConnection() {
        if (conn == null) {
            try {
                this.conn = dataSource.getConnection();
                this.conn.setAutoCommit(this.autoCommit);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public Connection getConnection()  {
        return conn;
    }
}

